﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Runtime.Remoting.Channels;

namespace CommonDB
{
    /// <summary>
    /// 实现sqlite数据库控制类
    /// </summary>
    public class SqliteProvider : IDbProvider
    {
        private string _connectionString;

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string ConnectionString
        {
            get
            {
                _connectionString = _connectionString ??
                                    System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                return _connectionString;
            }
            set
            {
                _connectionString = value;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public SqliteProvider()
        {
            _connectionString =
               System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

            CheckConnectString();
        }

        /// <summary>
        /// 检查数据库连接字符串
        /// </summary>
        private void CheckConnectString()
        {
            if (string.IsNullOrWhiteSpace(_connectionString))
            {
                throw new ArgumentNullException(_connectionString, "数据库连接字符串不能为空，请配置连接字符串！");
            }

            var startIndex = _connectionString.IndexOf("Data Source", StringComparison.OrdinalIgnoreCase);
            if (startIndex == -1)
            {
                throw new FileNotFoundException("没有找到指定的数据库文件！");
            }
            startIndex = _connectionString.IndexOf("=", startIndex, StringComparison.OrdinalIgnoreCase);
            var endIndex = _connectionString.IndexOf(";", startIndex, StringComparison.OrdinalIgnoreCase);
            var filename = endIndex == -1 ?
                _connectionString.Substring(startIndex + 1) :
                _connectionString.Substring(startIndex + 1, endIndex - startIndex);
            filename = filename.TrimEnd(';');
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("没有找到指定的数据库文件！");
            }
        }

        private IDbConnection _connection = null;
        /// <summary>
        /// 数据库连接对象
        /// </summary>
        public IDbConnection Connection
        {
            get
            {
                _connection = _connection ?? new SQLiteConnection(_connectionString);
                return _connection;
            }
            set
            {
                _connection = value;
            }
        }

        private IDbCommand _command = null;
        /// <summary>
        /// 数据库命令操作对象
        /// </summary>
        public IDbCommand Command
        {
            get
            {
                _command = _command ?? new SQLiteCommand(_connection as SQLiteConnection);
                return _command;
            }
            set
            {
                _command = value;
            }
        }

        private IDbDataAdapter _adapter = null;
        /// <summary>
        /// 数据库适配器对象
        /// </summary>
        public IDbDataAdapter Adapter
        {
            get
            {
                _adapter = _adapter ?? new SQLiteDataAdapter(_command as SQLiteCommand);
                return _adapter;
            }
            set
            {
                _adapter = value;
            }
        }

        /// <summary>
        /// 数据库事务对象
        /// </summary>
        private IDbTransaction _transaction = null;

        /// <summary>
        /// 打开数据库连接
        /// </summary>
        public void Open()
        {
            if (_connection != null && _connection.State != ConnectionState.Open)
            {
                _connection.Open();
            }
        }

        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void Close()
        {
            if (_connection != null)
            {
                _connection.Close();
            }
        }

        /// <summary>
        /// 开始事务
        /// </summary>
        public void BeginTransaction()
        {
            _transaction = _connection.BeginTransaction();
            Command.Transaction = _transaction;
        }

        /// <summary>
        /// 事务回滚
        /// </summary>
        public void RollBack()
        {
            if (_transaction != null)
            {
                _transaction.Rollback();
            }
        }

        /// <summary>
        /// 事务提交
        /// </summary>
        public void Commit()
        {
            if (_transaction != null)
            {
                _transaction.Commit();
            }
        }

        /// <summary>
        /// 释放内存空间
        /// </summary>
        public void Dispose()
        {
            if (_transaction != null)
            {
                _transaction.Dispose();
                _transaction = null;
            }
            if (_adapter != null)
            {
                _adapter.SelectCommand = null;
                _adapter = null;
            }
            if (_command != null)
            {
                _command.Transaction = null;
                _command.Connection = null;
                _command.Dispose();
                _command = null;
            }
            if (_connection != null)
            {
                _connection.Close();
                _connection.Dispose();
                _connection = null;
            }
            GC.SuppressFinalize(this);
        }
    }
}
